# encoding: utf-8 

import sys
import struct
import modbus_tk.defines as cst
import modbus_tk.modbus
import modbus_tk.modbus_tcp
import string
import time
import threading
import logging
import logging.handlers
import socket

# 对logging级别的分类
# 默认的等级是WARNING，也就是说logging函数在没有特别配置的前提下只追踪比WARNING程度更严重的异常
# LEVELS={'notset':logging.DEBUG,  
  
#         'debug':logging.DEBUG,  
  
#         'info':logging.INFO,  
  
#         'warning':logging.WARNING,  
  
#         'error':logging.ERROR,  
  
#         'critical':logging.CRITICAL} 


# define the log file, file mode and logging level
logging.basicConfig(filename='testIP.log', filemode="w", level=logging.debug)

# 通过modbus_tk封装的logger,控制台和文本都会有输出，而logging输出只将log输出到文本，控制台不会有打印
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
logger = modbus_tk.utils.create_logger(name="console", record_format=fmt)

class MyThread1(threading.Thread):
    
    def __init__(self, name, counter, host):
        threading.Thread.__init__(self)
        self.name = name
        self.counter = counter
        self.host = host
    def run(self):
        #print "Starting " + self.name

        # 连接MODBUS TCP从机，host参数为slave的IP地址
        master = modbus_tk.modbus_tcp.TcpMaster(host=self.host)
        master.set_timeout(3.0)
        try:
            # 读保持寄存器
            # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 26))
            # logger.info(self.host + " is connected")
            # 此处用logging，防止控制台大面积打印，把所有内容都打印到log文件，只把exception打印到控制台
            logging.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 26))
            logging.info(self.host + " is connected")
        except socket.timeout:   # connection timeout exception
            logger.info((self.host + " is not connected=========="))
      
            logger.info(self.host + "===============Exception====================")
        finally:
            print ("Exiting " )+ self.name


# 启用多线程，可同时对for循环中的每个IP地址进行连接测试，而避免如果一个IP连接不通则整个for循环就中途停止
for i in range(100, 125):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(130, 150):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(10, 35):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(60, 72):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(40, 49):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(50, 56):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(75, 97):
    hostIP = "127.0.0.1." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()